package cn.momoshenchi;


import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @version : 1.0
 * @author: momoshenchi
 * @date: 2021/2/12 - 18:38
 */
@ControllerAdvice
public class GlobalExceptionHandler
{
    /**
     * 难点在于是否json
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map<String, Object> handle(Exception e, HttpServletRequest request) throws Exception
    {
        e.printStackTrace();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "系统异常");
        if (e instanceof BindException)
        {
            BindException bindException = (BindException) e;
            map.put("code", 500);
            map.put("msg", bindException.getBindingResult().getFieldError().getDefaultMessage());
        }
        else if(e instanceof  ParamsException){
            ParamsException paramsException = (ParamsException) e;
            map.put("code", paramsException.getCode());
            map.put("msg", paramsException.getMsg());
        }
        return map;
    }

}

